<?php
  include 'header.php';
  include 'functions.php';
  include 'show_smilies.php';
  $pageTitle = "Quote";
  $hide_footer = 1;
  $fid = "";
  $userid = -5;
  if (isset($_SESSION['user_id']))
  {$userid = $_SESSION['user_id'];}
  
  if (!isset($_SESSION['signed_in'])) {
      //the user is not signed in
      echo '<hr><br /><div align="center"><span style="color:red">' . $l_you_need_to . ' <a href="signin.php">' . $l_login_s . '</a> ' . $l_in_order . ' <br>' . $l_u_also . ' <a href="signup.php">' . $l_register_s . '</a> ' . $l_for_acc . '</span></div><br />';
  } else {
      if ($_SERVER['REQUEST_METHOD'] != 'POST') {
	  if(!is_numeric($_GET['t'])){
      header('location: index.php');
      }
	  
	  
          if (isset($_GET['p'])) {
              $sql = $db->query("SELECT post_content, post_by, post_id FROM " . $table_prefix . "posts WHERE post_id = " . mysql_real_escape_string($_GET['p']) . " AND post_topic = " . mysql_real_escape_string($_GET['t']) . "");
              
              if (!$sql) {
                  header('location: topic.php?t=' . mysql_real_escape_string($_GET['t']) . '');
                  die;
              }
              $result = $db->query("SELECT topic_status FROM " . $table_prefix . "topics WHERE topic_id = " . mysql_real_escape_string($_GET['t']) . "");
              $check_status = $db->fetch_array($result,'assoc');
              if ($check_status['topic_status'] == 1 and $_SESSION['user_level'] < 1) {
                  echo '<div align="center">' . $l_error_tlocked . ' </div>';
              } else {
                  if (!$sql) {
                      echo 'The post could not be displayed, please try again later.';
                  } else {
                      if (mysql_num_rows($sql) == 0) {
                          echo 'This post doesn&prime;t exist.';
                      } else {
                          $text = $db->fetch_array($sql,'assoc');
                          
                          if ($default_wysiwyg == "1") {
                              $default_editor = "";
                          }
                          if ($default_wysiwyg != "1") {
                              $default_editor = "initEditor(\"reply\", true);  SwitchEditor()";
                          }
                          
                          echo '<table><tr><th>&nbsp;&nbsp;&nbsp;<b>' . $l_new_post . '</b></th></tr></table>';
						  
						 /*$text = preg_replace(
						  '/<div class=\"quote\"><div class=\"quoting\">(.+?): <\/div>(.+?)<\/div>/is', 
						  '[quote=\\1]\\2[/quote]', 
						  $text);
						  
						  $text = preg_replace(
						  '/<div class=\"quote\">(.+?): <\/div>(.+?)<\/div>/is', 
						  '[quote=\\1]\\2[/quote]', 
						  $text);
						  */
                          $text = BBDecode($text);
                          $text = str_replace("<br>", "\n", $text);
                          $text = str_replace('iframe', '%69%66%72%61%6D%65', $text);
                          //$text = preg_replace('/\[quote(.+?)\][\r\n]*(.+?)\[\/quote\][\r\n]*/si', '[quote]\\1: \\2[/quote]', $text);
                          $editor_css = "./style/$default_style/editor_reply.css";
                          $editor = "./style/$default_style/editor.js";
                      }
                      $tags = array('{START_POSTFORM}', '{MORE_SMILIES}', '{DISABLE_SMILIES}', '{TEXT_POST}', '{F_ID}', '{T_ID}', '(PAGE)', '{PN}', '{P}', '{EDIT_BUTTON}', '{U_ID}', '{IF_SMILIES}', '{END_SMILIES}', '{EDITOR_CSS}', '{EDITOR}', '{WYSIWYG}','(SUBMIT_REPLY)','{PREVIEW}','{DISABLE_BB}');
                      $data = array('', $l_more_smilies, $l_dissmilies, '[quote=' . $u_id . ']' . $text['post_content'] . '[/quote]', $fid, $topicid, $page, $pn, $page, 'New post', mysql_real_escape_string($_GET['u']), '', '', $editor_css, $editor, $default_editor,$l_submit_reply,$l_preview_button,$l_disable_bb);
                      
                      if ($allow_smilies == 0) {
                          $tags = array('{START_POSTFORM}', '{MORE_SMILIES}', '{DISABLE_SMILIES}', '{TEXT_POST}', '{F_ID}', '{T_ID}', '(PAGE)', '{PN}', '{P}', '{EDIT_BUTTON}', '{U_ID}', '{IF_SMILIES}', '{END_SMILIES}', '{EDITOR_CSS}', '{EDITOR}', '{WYSIWYG}','(SUBMIT_REPLY)','{PREVIEW}','{DISABLE_BB}');
                          $data = array('', $l_more_smilies, $l_dissmilies, '[quote=' . $u_id . ']' . $text['post_content'] . '[/quote]', $fid, $topicid, $page, $pn, $page, 'New post', mysql_real_escape_string($_GET['u']), '<!--', '-->', $editor_css, $editor, $default_editor,$l_submit_reply,$l_preview_button,$l_disable_bb);
                      }
                      
                      echo str_replace($tags, $data, file_get_contents('./style/' . $default_style . '/quote.html'));
                  }
              }
          } else {
              $pageTitle = "$l_reply";
              if ($default_wysiwyg == "1") {
                  $default_editor = "";
              }
              if ($default_wysiwyg != "1") {
                  $default_editor = "initEditor(\"reply\", true);  SwitchEditor()";
              }
              echo '<table><tr><th>&nbsp;&nbsp;&nbsp;<b>New post</b></th></tr></table>';
              $editor_css = './style/' . $default_style . '/editor_reply.css';
              $editor = './style/' . $default_style . '/editor.js';
              $tags = array('{START_POSTFORM}', '{MORE_SMILIES}', '{DISABLE_SMILIES}', '{TEXT_POST}', '{F_ID}', '{T_ID}', '(PAGE)', '{PN}', '{P}', '{EDIT_BUTTON}', '{U_ID}', '{IF_SMILIES}', '{END_SMILIES}', '{EDITOR_CSS}', '{EDITOR}', '{WYSIWYG}','(SUBMIT_REPLY)','{PREVIEW}','{DISABLE_BB}');
              $data = array('', $l_more_smilies, $l_dissmilies, '', $fid, $topicid, $page, $pn, $page, 'New post', $u_id, '', '', $editor_css, $editor, $default_editor,$l_submit_reply,$l_preview_button,$l_disable_bb);
              
              if ($allow_smilies == 0) {
                  $tags = array('{START_POSTFORM}', '{MORE_SMILIES}', '{DISABLE_SMILIES}', '{TEXT_POST}', '{F_ID}', '{T_ID}', '(PAGE)', '{PN}', '{P}', '{EDIT_BUTTON}', '{U_ID}', '{IF_SMILIES}', '{END_SMILIES}', '{EDITOR_CSS}', '{EDITOR}', '{WYSIWYG}','(SUBMIT_REPLY)','{PREVIEW}','{DISABLE_BB}');
                  $data = array('', $l_more_smilies, $l_dissmilies, '', $fid, $topicid, $page, $pn, $page, $l_new_post, $u_id, '<!--', '-->', $editor_css, $editor, $default_editor,$l_submit_reply,$l_preview_button,$l_disable_bb);
              }
              
              echo str_replace($tags, $data, file_get_contents('./style/' . $default_style . '/quote.html'));
          }
      } else {
          // Check if message contain only spaces
          $spaces = array('&nbsp;');
          $_POST["reply"] = str_replace($spaces, ' ', $_POST["reply"]);
          
          //a real user posted a real reply
          $blah = $_POST["reply"];
          if ((strlen($blah) < $min_post_characters) or (preg_match('|^\s*\z|', $_POST["reply"]))) {
              echo "<hr><br><div align=\"center\"><span style='color:red'>$l_message_few<br /><br /></span>
<a href='topic.php?f=" . mysql_real_escape_string($_GET['f']) . "&t=" . mysql_real_escape_string($_GET['t']) . "'>$l_back_to_prev</a></div><br><br>";
          } else {
              if ((strlen($blah) > $max_post_characters)) {
                  echo "<hr><br><div align='center'><span style='color:red'>$l_message_many<br /><br /></span>
<a class=\"loginlink\" href='topic.php?t=" . mysql_real_escape_string($_GET['t']) . ">$l_back_to_prev</a></div><br><br>";
              } else {
                  $text = $_POST['reply'];
				  $text = my_nl2br($text); //Remove double or miltiple new lines
                  $text = convEnt2($text);
                  $text = str_replace("\n", "<br>", $text);
                  
                  //Disable smilies in post?
                  $disable_smilies = "0";
                  if (isset($_POST['dissmilies']) && $_POST['dissmilies'] == 'on') {
                      $disable_smilies = "1";
                      $text = DisableSmilies($text);
                  }
                  //Parse BBCodes
                  if (!isset($_POST['dissbb'])) {
                          $text = BBCode($text);
                      }
                  $result1 = $db->query("SELECT topic_id, topic_subject, topic_cat, view, reply FROM " . $table_prefix . "topics WHERE topics.topic_id = " . mysql_real_escape_string($_GET['t']));

                  $result2 = $db->query("SELECT post_by, post_topic FROM " . $table_prefix . "posts WHERE post_topic = " . mysql_real_escape_string($_GET['t']) . "");
                  $tsubject = $db->fetch_array($result1,'assoc');
                  $perma_link = mysql_num_rows($result2) + 1;
                  $userIP = $_SERVER["REMOTE_ADDR"];
                  $post_page = ceil($perma_link / $post_per_page);
                  if ($post_page == "") {
                      $post_page = 1;
                  }
				  $user = $db->query("SELECT user_name, user_posts  FROM " . $table_prefix . "users WHERE user_id = " . $_SESSION['user_id'] . " LIMIT 1");
                  $userposted = $db->fetch_array($user,'assoc');
				  $approve = 0;
				  if ($post_approve == 1 AND $_SESSION['user_level']<1 AND $userposted['user_posts']<$auto_approve_after_posts) {$approve = 1;}
					  if ($post_approve == 1 AND $_SESSION['user_level']<1 AND $auto_approve_after_posts == 0) {$approve = 1;}
				  
                  $result = $db->query("INSERT INTO " . $table_prefix . "posts (
				  post_subject, 
				  post_content, 
				  post_date, 
				  post_topic, 
				  post_by, 
				  post_smilies, 
				  poster_ip, 
				  post_cat,
				  post_page,
				  post_approve) 
				  VALUES (
				  '$tsubject[topic_subject]',
				  '$text',
				  NOW() + INTERVAL $server_time MINUTE + INTERVAL $time_difference HOUR ,
				  " . mysql_real_escape_string($_GET['t']) . ",
				  " . $userid.", 
				  $disable_smilies, 
				  '$userIP',
				  $tsubject[topic_cat],
				  $post_page, 
				  $approve)");

                  $postid = mysql_insert_id();
                  				  				  
                  //UPDATE categories
                  //all topics
                  $result44 = $db->query("SELECT reply FROM " . $table_prefix . "topics WHERE topic_cat = " . $tsubject['topic_cat'] . "");
                  $topics = mysql_num_rows($result44);
                  //all replies
                  $result55 = $db->query("SELECT SUM(reply) FROM " . $table_prefix . "topics WHERE topic_cat = " . $tsubject['topic_cat'] . "");
                  $row5 = $db->fetch_array($result55,'assoc');
                  $num_replies = $row5['SUM(reply)'];
                  
                  $result5 = $db->query("UPDATE " . $table_prefix . "categories SET cat_last_post_id=" . mysql_real_escape_string($_GET['t']) . ", cat_last_poster_id=" . $_SESSION['user_id'] . ",cat_last_post_subject='" . $tsubject['topic_subject'] . "',cat_last_post_time=NOW() + INTERVAL " . $server_time . " MINUTE + INTERVAL " . $time_difference . " HOUR, cat_last_poster_name='" . $userposted['user_name'] . "',cat_posts=$num_replies+1,cat_topics=$topics WHERE cat_id = " . $tsubject['topic_cat'] . "") or die(mysql_error());
                  
                  //Cache this topic
                  if ($forum_cache == 1) {
                      $time = strtotime($time_difference . " hours");
                      $cache = "./cache/forum" . $tsubject['topic_cat'] . ".php";
                      $FileHandle = fopen($cache, 'w') or die("can't open file");
                      fwrite($FileHandle, "ForumID = " . $tsubject['topic_cat'] . "");
                      fwrite($FileHandle, "\nTopicID = " . mysql_real_escape_string($_GET['t']) . "");
                      fwrite($FileHandle, "\nLast Topic = " . $tsubject['topic_subject'] . "");
                      fwrite($FileHandle, "\nTopic date = " . date($date_format, $time) . "");
                      fwrite($FileHandle, "\nTopic by = " . $userposted['user_name'] . "");
                      fwrite($FileHandle, "\nUserID = " . $_SESSION['user_id'] . "");
                      fwrite($FileHandle, "\nTopics = " . $topics . "");
                      fwrite($FileHandle, "\nReplies = " . $num_replies . "");
                      fclose($FileHandle);
                  }
                  //Cache this topic
                  
                  $result4 = $db->query("UPDATE " . $table_prefix . "topics SET topic_last_poster='" . $userposted['user_name'] . "', topic_last_post_date= NOW() + INTERVAL " . $server_time . " MINUTE + INTERVAL " . $time_difference . " HOUR , reply=" . mysql_num_rows($result2) . ", topic_last_poster_id = " . $_SESSION['user_id'] . "  WHERE topic_id=" . mysql_real_escape_string($_GET['t']));
                  
                  $result5 = $db->query("UPDATE " . $table_prefix . "users set user_posts=user_posts+1 WHERE user_id = " . $_SESSION['user_id'] . "");
                  
                  if (!$result) {
                      echo 'Your reply has not been saved, please try again later.';
                  } else {
                      $topic_page = $page;
                      if ($topic_page == "") {
                          $topic_page = 1;
                      }
                      //CHECK notifications
                      $result = $db->query("SELECT * FROM " . $table_prefix . "topics_watch WHERE topic_id = " . $tsubject['topic_id'] . " AND user_id !=" . $_SESSION['user_id'] . " AND status = 0");
                      if (mysql_num_rows($result) <= 0) {
                          echo "";
                      } else {
                          while ($row = $db->fetch_array($result,'assoc')) {
                              $result2 = $db->query("SELECT  user_email, user_name FROM " . $table_prefix . "users WHERE user_id = " . $row['user_id'] . "") or die(mysql_error());
                              $row2 = $db->fetch_array($result2,'assoc');
                              $result3 = $db->query("UPDATE " . $table_prefix . "topics_watch SET status = 1 WHERE user_id = " . $row['user_id'] . "");
                              
                              //echo $row2['user_email']." - ".$row2['user_name']."<br>";
                              $email = $row2['user_email'];
                              $url = "http://" . $_SERVER["SERVER_NAME"] . dirname($_SERVER["PHP_SELF"]) . "/topic.php?t=" . $tsubject['topic_id'] . "&page=" . $topic_page;
                              $unnotify = "http://" . $_SERVER["SERVER_NAME"] . dirname($_SERVER["PHP_SELF"]) . "/topic.php?t=" . $tsubject['topic_id'] . "&unnotify=" . $tsubject['topic_id'];
                              
                              $subject = "Topic reply: " . $tsubject['topic_subject'];
                              $message = "$l_email_message1 " . $row2['user_name'] . ",\r\n\r\n";
                              $message .= "$l_email_notify1 " . $tsubject['topic_starter'] . ". \r\n\r\n";
                              $message .= "$l_email_notify2 " . $url . "#$postid\r\n\r\n";
                              $message .= "$l_email_notify3 " . $unnotify . "\r\n\r\n";
                              $message .= $l_email_notify4;
                              
                              if ($smtp == "local") {
                                  $myemail = $smtp_username;
                                  //$row2['user_email'];    //"$_POST[user_email]";
                                  $to = $row2['user_email'];
                                  $subject = $subject;
                                  $sendmessage = $message;
                                  $headers = "From: $l_forumname<$myemail>" . "\r\n" . "Reply-To: $myemail" . "\r\n" . 'X-Mailer: PHP/' . phpversion();
                                  $sentmail = mail($to, $subject, $sendmessage, $headers);
                              }
                              //END LOCAL mail
                              //SMTP MAIL
                              if ($smtp == "smtp") {
                                  error_reporting(E_STRICT);
                                  date_default_timezone_set('America/Toronto');
                                  require_once('./phpmailer/class.phpmailer.php');
                                  $mail = new PHPMailer();
                                  
                                  $body = "Hello " . $row2['user_name'] . ",\r\n\r\n<br /><br />";
                                  $body .= "$l_email_notify1 " . $tsubject['topic_starter'] . ". \r\n\r\n<br /><br />";
                                  $body .= "$l_email_notify2 " . $url . "#$postid\r\n\r\n<br /><br />";
                                  $body .= "$l_email_notify3 " . $unnotify . "\r\n\r\n<br /><br />";
                                  $body .= $l_email_notify4;
                                  $body = preg_replace("#[\]#", '', $body);
                                  
                                  // telling the class to use SMTP
                                  $mail->IsSMTP();
                                  // SMTP server
                                  $mail->Host = $smtp_server;
                                  // enables SMTP debug information (for testing)
                                  $mail->SMTPDebug = 1;
                                  // 1 = errors and messages, 2 = messages only
                                  // enable SMTP authentication
                                  $mail->SMTPAuth = true;
                                  // sets the SMTP server
                                  $mail->Host = $smtp_server;
                                  $mail->SMTPSecure = $smtp_secure;
                                  // set the SMTP port for the GMAIL server
                                  $mail->Port = $smtp_port;
                                  // SMTP account username
                                  $mail->Username = $smtp_username;
                                  // SMTP account password
                                  $mail->Password = $smtp_password;
                                  
                                  $mail->SetFrom($smtp_username, $l_forumname);
                                  $mail->AddReplyTo($row2['user_email'], $l_forumname);
                                  $mail->Subject = "$l_email_notify_subject " . $tsubject['topic_subject'];
                                  // optional, comment out and test
                                  $mail->AltBody = "$l_email_alt_body";
                                  $mail->MsgHTML($body);
                                  $address = $row2['user_email'];
                                  $mail->AddAddress($address, $row2['user_name']);
                                  
                                  if (!$mail->Send()) {
                                      echo "Mailer Error: " . $mail->ErrorInfo;
                                  }
                              }
                              //END SMTP MAIL
                              
                          }
                      }
                      $pages = ceil($perma_link / $post_per_page);
                      $topic_page = $pages;
                      if ($topic_page == "") {$topic_page = 1;}
                      
                      if (isset(mysql_real_escape_string($_GET['p']))) {
                          echo '<hr/><br/><div align="center">' . $l_posted_success . '<br /><br /> <a class="loginlink" href="topic.php?f=' . $fid . '&t=' . $topicid . '&page=' . $topic_page . '#' . $perma_link . '">' . $l_view_message . '</a>.<br /><a class="loginlink" href="category.php?f=' . $fid . '"><br /> ' . $l_return_to . '</a>. </div><br />';
                      } else {
                          echo '<hr/><br/><div align="center">' . $l_posted_success . '<br /><br /> <a class="loginlink" href="topic.php?t=' . $topicid . '&page=' . $topic_page . '#' . $postid . '">View your submitted message</a>.<br /><a class="loginlink" href="category.php?f=' . $tsubject['topic_cat'] . '"><br /> ' . $l_return_to . '</a>. </div><br />';
                      }
                  }
              }
          }
      }
  }
  if ($hide_footer < 1) {
      include 'footer.php';
  }
  
  $pageContents = ob_get_contents();
  ob_end_clean();
  echo str_replace('<!--TITLE-->', $pageTitle, $pageContents);
?>
